<?php
namespace app\index\controller;
use think\Controller;

use app\index\model\Goods;

class Index extends Controller
{

      

    
	// 购物车页面
    public function index()
    {
    	$redis = new \Redis();
        $redis->connect('127.0.0.1',6379);

       
        $data = Goods::select();
        $this->assign('data',$data);    // 展示数据库里的商品列表


        $cat = $redis->hGetAll('cart_1');  // 根据redis中的数据展示购物车列表数据
        foreach ($cat as $key => $value) {
            $res[$key] = Goods::where('id',$key)->find();
            $res[$key]['num'] = $value;         
        }
        $this->assign('res',$res);
        return $this->fetch();
    }
    // 添加购物车
    public function addcart($userid='1',$goodid)
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $hashKey = 'cart_'.$userid;  //hash名称
        $key = $goodid; //hsah键名
        $redis->hincrby($hashKey,$key,1); //设置hash键名+1
        echo "111";
    }

    // 删减购物车
    public function delcart($userid='1',$goodid)
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $hashKey = 'cart_'.$userid;  //hash名称
        $key = $goodid; //hsah键名
        $a = $redis->hget($hashKey,$key);
        if($a>=1){
            $redis->hincrby($hashKey,$key,-1); //设置hash键名-1
        }else{
            echo "无法再减的哦";
        }
        
    }

    /**
     * 用户清空购物车
     * @param $userid 用户id
     */
    public function del($userid)
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $hashKey = 'cart_'.$userid;
        $redis->del($hashKey);
    }

    /**
     *用户移除购物车中某件商品(可以根据商品id获取商品名称,这里为了方便)
     * @param $userid
     * @param $goodid
     */
    public function removecart($userid,$goodid)
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $hashKey = 'cart_'.$userid;  //hash名称
        $key = $goodid; //hsah键名
        $redis->hdel($hashKey,$key);
    }

    /**
     * 获取购物车的全列表
     */

    public function getCartList($userid)
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $hashKey = 'cart_'.$userid;  //hash名称
        $data = $redis->hGetAll($hashKey);
        return $data;
    }

}
